/* 
Copyright (c) 2008 Delio Brignoli

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/

#include <Adac.h>
#include <stdlib.h>

#define NUM_INPUTS 4

struct conv_callback_state_struct {
  //Inputs sequence
  int inputs[NUM_INPUTS];
  int nextInputIndex;

  //Results ringbuffer
  int results[NUM_INPUTS*4];
  int nextResultIndex;
};

void setup() {
  adac_init();
}

void conversion_complete(int conversion_count, void* priv) {
  
  conv_callback_state_struct *state = (conv_callback_state_struct *)priv;
  
  if (conversion_count == 0) {
    state->nextInputIndex = 0;
    state->nextResultIndex = 0;
  } else {
    state->results[state->nextResultIndex++ % sizeof(state->results)] = adac_read_result();
  }

  //Set next input to a negative value will stop the conversion
  adac_set_next_input(state->inputs[state->nextInputIndex++ % sizeof(state->nextInputIndex)]);
}

void loop() {
  conv_callback_state_struct callback_state;

  callback_state.inputs[0] = 1;
  callback_state.inputs[1] = 2;
  callback_state.inputs[2] = 3;
  callback_state.inputs[3] = 4;
  
  adac_prepare(callback_state.inputs, sizeof(callback_state.inputs), &conversion_complete, (void*)&callback_state);
  adac_trigger();
  adac_pause();
  adac_stop();
}
